<template>
	<view>
	</view>
</template>
<script>
	let isRecording = false;
	let mediaRecorder;
	let audioChunks = [];
	let messageCount = 0;
	let serverFinTim = localStorage.getItem('finish_time');
	// let markid = getQueryString('mark_id');
	// console.log(markid);

	// document.addEventListener('DOMContentLoaded', () => {
	// 	const timestamp = parseInt(new Date().getTime() / 1000);
	// 	let orderNo = getQueryString('order_no');
	// 	if ((serverFinTim == null || serverFinTim - timestamp < 0) && orderNo != null) {
	// 		console.log(123);
	// 		setTimeout(() => {
	// 			getOrderResult(orderNo);
	// 		}, 1000);
	// 	}
	// 	loadChatHistory();
	// 	console.log(serverFinTim - timestamp);
	// 	if (serverFinTim != null && serverFinTim - timestamp > 0) {
	// 		console.log('finish_time');
	// 		startCountdown(serverFinTim - timestamp);
	// 	}
	// });
import COS from 'cos-js-sdk-v5';
export default {
	data() {
	  return {
	    title: '充值提醒',
		content: '20元120张聊天记录图分析, 每次最多可以传入4张照片',
	    fileList1: [],
	    availableTimes: 0, // 可用次数
	    membershipExpiry: "", // 会员到期时间
	    showOverlay: false, // 控制浮层显示
	    analysisResult: "", // 分析结果
	    loading: false, // 控制加载提示
		orderNo: "",
		show: true,
		countdown: 60,
		userInput: '',
		commentScrollTop: 0,
		showBuy: false,
		messages: [],
		sending: false,
		order_no: '',
		id: 0,
		user_id: ''
	  };
	},
	onLoad(options) {
		console.log(123);
		this.id = options.id;
		this.user_id = options.user_id;
		this.order_no = options.order_no;
		this.handleWeChatCallback();
	},
	methods: {
		saveOpenID(openid) {
		  localStorage.setItem('openid', openid);
		},
		async handleWeChatCallback() {
		  const urlParams = new URLSearchParams(window.location.search);
		  const code = urlParams.get('code');
		  console.log(code);
		  if (code) {
		    try {
		      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/login?code=${code}`);
		      const data = await response.json();
		      console.log(data.data.open_id);
		      if (data.data.open_id) {
		        this.saveOpenID(data.data.open_id);
		        // this.getAvailableTimes(data.data.open_id); // 获取可用次数和会员到期时间
		        // window.history.replaceState({}, document.title, window.location.pathname);
		      } else {
		        console.error('Failed to get openid from server');
		      }
		    } catch (error) {
		      console.error('Error during WeChat login:', error);
		    }
		  } else {
		    this.checkOpenID();
		  }
		  
		  this.rechargeMembership();
		  // this.getResponse();
		},
		checkOpenID() {
		  const openid = localStorage.getItem('openid');
		  console.log(openid);
		  if (openid) {
		    // this.getAvailableTimes(openid); // 获取可用次数和会员到期时间
		  } else {
		    this.weChatLogin();
		  }
		},
		weChatLogin() {
		  const appId = 'wxad67b499443b7a4b';
		  const redirectUri = encodeURIComponent(window.location.href);
		  const weChatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`;
		  window.location.href = weChatAuthUrl;
		},
		initChat() {
			
		},

	getQueryString(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
	},

	async rechargeMembership() {
	  // 请求服务端获取微信支付参数
	  console.log('recharge');
	  try {
	    const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
	      method: 'POST',
	      headers: {
	        'Content-Type': 'application/json'
	      },
	      body: JSON.stringify({
	        open_id: localStorage.getItem('openid'),
			type: 2,
			user_id: this.user_id
	      })
	    });
	    const data = await response.json();
			  this.orderNo = data.data.order_no;
			  
			  if (typeof WeixinJSBridge == "undefined") {
			      if (document.addEventListener) {
			          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			      } else if (document.attachEvent) {
			          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			      }
			  } else {
			      this.onBridgeReady(data);
			  }
			} catch (error) {
			  console.error('请求支付参数时出错:', error);
			}
	},
	
	onBridgeReady(data) {
			  var that = this
			  WeixinJSBridge.invoke('getBrandWCPayRequest', {
			      "appId": data.data.appId,     //公众号ID，由商户传入     
			      "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
			      "nonceStr": data.data.nonceStr,      //随机串     
			      "package": data.data.package,
			      "signType": "MD5",     //微信签名方式：     
			      "paySign": data.data.paySign,
			  },
			  function(res) {
			      if (res.err_msg == "get_brand_wcpay_request:ok") {
			          // 使用以上方式判断前端返回,微信团队郑重提示：
			          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
			  		  that.pollPaymentResult();
			      }
			  });
	},
	cancel() {
			  this.show = false;
	},
	async pollPaymentResult() {
	  const pollInterval = 1000; // 轮询间隔时间（毫秒）
	  const maxAttempts = 20; // 最大轮询次数
	  let attempts = 0;
			const orderNo = this.orderNo;
	  const poll = async () => {
	    try {
	      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
	      const data = await response.json();
	      if (data.code === 0) {
	        // 支付成功
	        // alert('充值成功');
	        // this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
	        return;
	      } else if (data.code === 1) {
	        // 支付进行中，继续轮询
	        if (attempts < maxAttempts) {
	          attempts++;
	          setTimeout(poll, pollInterval);
	        } else {
	          alert('支付结果查询超时');
	        }
	      } else {
	        // 支付失败
	        alert('支付失败');
	      }
	    } catch (error) {
	      console.error('查询支付结果时出错:', error);
	      alert('查询支付结果时出错');
	    }
	  };
	
	  poll();
	}
	},
}
</script>


<style>
	body {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
		background-color: #f5f5f5;
		margin: 0;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}
	.message-list {
		flex-grow: 1; /* 占用所有可用空间 */
		overflow-y: auto; 
		margin-top: 15rpx;
	}
	.chat-container {
		margin-top: 3rpx;
		display: flex;
		  flex-direction: column;
		  height: 100%; 
	}
	.chat-header {
		background-color: #dcf8c6;
		color: white;
		/* padding: 10px 20px; */
		/* display: flex; */
		/* align-items: center; */
		display: flex;
		justify-content: center;
		/* margin-top: 10px; */
		/* margin-bottom: 1px; /* 添加底部间距 */
	}
	.chat-header img {
		border-radius: 50%;
		width: 80px;
		height: 60px;
		margin-right: 20px;
	}
	.chat-header .info-container {
		display: flex;
		flex-direction: column;
	}
	.chat-header .intro {
		font-size: 16px;
		margin: 5px 0;
	}
	.chat-header .intro:first-child {
		font-weight: bold;
	}
	.countdown-timer {
		font-size: 16px;
		font-weight: bold;
		color: white;
		margin-top: 5px;
	}
	.chat-box {
		flex: 1;
		overflow-y: auto;
		padding: 20px;
		display: flex;
		flex-direction: column;
	}
	.chat-message {
		margin: 10px 0;
		display: flex;
		flex-direction: column;
	}
	.chat-message.user {
		align-items: flex-end;
	}
	.chat-message.picture {
		align-items: flex-end;
		margin-bottom: 100rpx;
	}
	.chat-message.bot {
		align-items: flex-start;
	}
	.chat-bubble {
		max-width: 70%;
		padding: 5px 5px;
		border-radius: 20px;
		line-height: 1.5;
		margin-bottom: 5px;
	}
	.chat-bubble.user {
		background-color: limegreen;
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.picture {
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.bot {
		background-color: #fff;
		border: 1px solid #ececec;
		border-radius: 20px 20px 20px 0;
	}
	.chat-input {
		display: flex;
		padding: 10px;
		border-top: 1px solid #ececec;
		background-color: #fafafa;
		align-items: center;
	}
	.chat-input input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
	}
	.chat-input button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		flex-shrink: 0;
		height: 40px;
	}
	.chat-input button.voice {
		margin-left: 10px;
	}
	.chat-input button:hover {
		background-color: #005bb5;
	}
	.record-button {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
		background-color: white !important;
		color: black !important;
		cursor: pointer;
		text-align: center;
	}
	.toggle-button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		height: 40px;
	}
	.toggle-button:hover {
		background-color: #005bb5;
	}
	.small-button {
		padding: 5px 10px;
		font-size: 12px;
		margin-top: 5px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 10px;
		cursor: pointer;
	}
	.small-button:hover {
		background-color: #005bb5;
	}
	.converted-text {
		background-color: #f1f1f1;
		border: 1px solid #ececec;
		border-radius: 10px;
		padding: 10px;
		margin-top: 5px;
		font-style: italic;
		color: #333;
	}
	.payment-overlay {
		display: flex;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
		flex-direction: column;
		z-index: 10;
	}
	.payment-message {
		/* background-color: #ffffff; */
		padding: 20px;
		border-radius: 10px;
		text-align: center;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		margin-bottom: 20px;
		font-size: 18px;
		width: 80%;
		color: #333;
	}
	.payment-button {
		padding: 5px 30px;
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		color: white;
		border: none;
		border-radius: 30px;
		cursor: pointer;
		font-size: 18px;
		font-weight: bold;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.payment-button:hover {
		background: linear-gradient(90deg, #ff6a4a, #fd9c6e);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
	}
	.fixed-buttons {
		position: fixed;
		bottom: 100px;
		right: 20px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}
	.role-button, .upload-button {
		padding: 10px 20px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 20px;
		cursor: pointer;
		font-size: 14px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.role-button:hover, .upload-button:hover {
		background-color: #005bb5;
	}
	.modal {
		display: none;
		position: fixed;
		z-index: 100;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
	}
	.modal-content {
		background-color: #fefefe;
		margin: 15% auto;
		padding: 20px;
		border: 1px solid #888;
		width: 80%;
		max-width: 400px;
		border-radius: 10px;
		text-align: center;
	}
	.close {
		color: #aaa;
		float: right;
		font-size: 28px;
		font-weight: bold;
	}
	.close:hover,
	.close:focus {
		color: black;
		text-decoration: none;
		cursor: pointer;
	}
	@media (max-width: 600px) {
		.chat-container {
			width: 100%;
			height: 100vh;
			border-radius: 0;
		}
		.chat-box {
			padding: 10px;
		}
		.chat-input input {
			font-size: 14px;
			padding: 8px;
		}
		.chat-input button {
			font-size: 14px;
			padding: 0 15px;
			height: 36px;
		}
		.record-button {
			padding: 8px;
			height: 36px;
		}
		.toggle-button {
			height: 36px;
		}
	}
</style>